import gtk
import glib
import hildondesktop
import dbus
import time
import math
import cairo

import n900dev
import ui
import log
import sched

class HomeScreen(hildondesktop.HomePluginItem):


    def __init__(self):

        hildondesktop.HomePluginItem.__init__(self)
        self.timeout_handler = glib.timeout_add(445, self.updates, self)
        
        self.gps = n900dev.GPS()
        self.cell = n900dev.Celluar()
        self.wifi = n900dev.Wlan()
        self.acc = n900dev.Accel()
        self.log = log.log()
        self.schedule = sched.scheduler(time.time, time.sleep)

        self.widgetui = ui.ui(self)        
        self.widgetui.draw()

        

    def updates(self,w):
        #print "--------"
        print time.time()
        self.acc_value = []
        self.gps.on()
        self.schedule.enter(0, 1, self.acc.read, ([20]))# read accelerometer
        self.acc_value.append(self.acc.coords)

        self.schedule.enter(0.5, 1, self.gps.read, ()) # read gps

        self.schedule.enter(1.5, 1, self.acc.read, ([20]))# read accelerometer
        self.acc_value.append(self.acc.coords)

        self.schedule.enter(2, 1, self.wifi.scan, ())# read wifi 

        self.schedule.enter(4, 1, self.acc.read, ([20]))# read accelerometer
        self.acc_value.append(self.acc.coords)

        self.schedule.enter(4.5, 1, self.cell.read, ())# read cell id

        self.schedule.run()
        #print time.time()
        
        if "lat" in self.gps.coords:
            self.widgetui.set_lat(self.gps.coords['lat'])
        if "lng" in self.gps.coords:
            self.widgetui.set_lng(self.gps.coords['lng'])
        self.widgetui.set_cell(self.cell.cell['cid'])
        self.widgetui.set_wifi(len(self.wifi.aps)-1)
        # read accelerometer
        #a = self.acc.read(100)
        # log data
        data = {}
        data['gps'] = self.gps.coords
        data['cell'] = self.cell.cell
        data['wifi'] = self.wifi.aps
        data['acc'] = self.acc_value
        self.log.save(data)
        #print time.time()
        return True
        
        
    def do_expose_event(s, e):
        a = e.area
        cr = s.window.cairo_create()
        cr.arc(a.width/2,a.height/2,a.width,0,2*math.pi)
        cr.set_source_rgba(0.0,0.0,0.0,0.625)
        cr.fill()
        hildondesktop.HomePluginItem.do_expose_event(s,e)

    def do_realize(s):
        scn = s.get_screen()
        cm = scn.get_rgba_colormap()
        s.set_colormap(scn.get_rgba_colormap())
        s.set_app_paintable(True)
        hildondesktop.HomePluginItem.do_realize(s)
    
    def do_destroy(self):
        import sys
        sys.exit(0)


# The code below is just for testing purposes.
# It allows to run the widget as a standalone process.
if __name__ == "__main__":
    pass

